package com.hualude.roadsign.service.impl;

import com.hualude.roadsign.dto.*;
import com.hualude.roadsign.repository.*;
import com.hualude.roadsign.service.CoverFaultService;
import com.hualude.roadsign.utils.PushUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by pjn on 2017/7/22.
 */
@Service
public class CoverFaultServiceImpl implements CoverFaultService {
    @Resource
    private CoverFaultRepository coverFaultRepository;
    @Resource
    private CoverRepository coverRepository;
    @Resource
    private UserRepository userRepository;
    @Resource
    private OrgRepository orgRepository;
    @Resource
    private PushHistoryRepository pushHistoryRepository;

    private String strUserIds;

    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    public DTResponseDto getCoverReportFault4DT(DTRequestDto dtRequestDto, Integer actorId, Integer userId, Integer orgId) throws Exception {
        Integer count;
        List<DTCoverFaultDto> dto4DTs;
        count = coverFaultRepository.getCoverReportFaultCount4DT(actorId, userId, orgId, dtRequestDto.getSearch());
        dto4DTs = coverFaultRepository.getCoverReportFault4DT(dtRequestDto, actorId, userId, orgId);
        for (DTCoverFaultDto dto : dto4DTs) {
            dto.setCoverCheckerName(userRepository.getUserNameByUserId(dto.getCoverCheckerId()));
        }
        DTResponseDto dtResponseDto = new DTResponseDto(dtRequestDto.getDraw(), count, count, dto4DTs);
        return dtResponseDto;
    }

    public CoverFaultDto getCoverInfo2Fault(Integer coverId) throws Exception {
        CoverFaultDto coverFaultDto;
        coverFaultDto = coverRepository.getCoverInfo2Fault(coverId);
        coverFaultDto.setCoverCreatorName(userRepository.getUserNameByUserId(coverFaultDto.getCoverCreatorId()));
        coverFaultDto.setCoverOrgName(orgRepository.getMainOrgName(coverFaultDto.getCoverOrgId()));
        coverFaultDto.setCoverMainOrgName(orgRepository.getMainOrgName(coverFaultDto.getCoverMainOrgId()));
        coverFaultDto.setCoverId(coverId);
        return coverFaultDto;
    }

    public CoverFaultDto getCoverFaultInfo2Fault(Integer coverId, Integer coverFaultId) throws Exception {
        CoverFaultDto coverFaultDto;
        coverFaultDto = coverRepository.getCoverInfo2Fault(coverId);
        CoverFaultDto coverFault = coverFaultRepository.getCoverFaultInfo2Fault(coverFaultId);
        coverFault.setCoverProvince(coverFaultDto.getCoverProvince());
        coverFault.setCoverCity(coverFaultDto.getCoverCity());
        coverFault.setCoverArea(coverFaultDto.getCoverArea());
        coverFault.setCoverRoadName(coverFaultDto.getCoverRoadName());
        coverFault.setCoverStartRoad(coverFaultDto.getCoverStartRoad());
        coverFault.setCoverEndRoad(coverFaultDto.getCoverEndRoad());
        coverFault.setCoverLongitude(coverFaultDto.getCoverLongitude());
        coverFault.setCoverLatitude(coverFaultDto.getCoverLatitude());
        coverFault.setCoverOrgId(coverFaultDto.getCoverOrgId());
        coverFault.setCoverMainOrgId(coverFaultDto.getCoverMainOrgId());
        UserDto userDto = userRepository.getUserById(coverFault.getCoverFaultCreatorId());
        coverFault.setCoverFaultCreatorName(userDto.getUserName());
        coverFault.setCoverFaultCreatorPhone(userDto.getUserMobile());
        return coverFault;
    }

    @Transactional
    public Integer updateCoverFault(Integer coverFaultId, Integer coverFaultLevel, Integer coverFaultType, String coverFaultPhoto, String coverFaultReason, Double coverMoney) throws Exception {
        return coverFaultRepository.updateCoverFault(coverFaultId, coverFaultLevel, coverFaultType, coverFaultPhoto, coverFaultReason, coverMoney);
    }

    @Transactional
    public Integer deleteCoverFaultByIds(String coverFaultIds) throws Exception {
        String[] faultIdArray = coverFaultIds.split(",");
        int i = 0;
        for (i = 0; i < faultIdArray.length; i++) {
            coverFaultRepository.deleteCoverFaultByIds(Integer.parseInt(faultIdArray[i]));
        }
        return i;
    }

    public List<CoverFaultDto> getCoverCoordinate4Map(Integer orgId, Integer actorId) throws Exception {
        return coverRepository.getCoverCoordinate4Map(orgId, actorId);
    }

    public List<CoverFaultDto> getCoverByXY(String longitude, String latitude) throws Exception {
        return coverRepository.getCoverByXY(longitude, latitude);
    }

    public DTResponseDto getCoverFaultReport4DT(DTRequestDto dtRequestDto, Integer actorId, Integer orgId, String coverRoadName, String coverStartRoad, String coverEndRoad) throws Exception {
        if (coverStartRoad.equals("") && coverEndRoad.equals("")) {
            return new DTResponseDto(dtRequestDto.getDraw(), 0, 0, "");
        } else {
            Integer count = coverRepository.getCoverFaultReportCount4DT(dtRequestDto.getSearch(), actorId, orgId, coverRoadName, coverStartRoad, coverEndRoad);
            List<DTCoverFaultDto> dto4DTs = coverRepository.getCoverFaultReport4DT(dtRequestDto, actorId, orgId, coverRoadName, coverStartRoad, coverEndRoad);
            for (DTCoverFaultDto dto : dto4DTs) {
                List<CoverFaultDto> coverFaultDtos = coverFaultRepository.getCoverFaultIsReport(dto.getCoverId());
                Integer result = 1;
                if (coverFaultDtos.size() != 0) {
                    Integer mainCheck = coverFaultDtos.get(0).getCoverMainCheck();
                    Integer check = coverFaultDtos.get(0).getCoverCheck();
                    Integer status = coverFaultDtos.get(0).getCoverMaintenanceStatus();
                    if (status == 2) {
                        result = 1;//维修完成
                    } else if (mainCheck == -1 || check == -1) {
                        result = 1;//
                    } else {
                        result = 0;
                    }
                }
                dto.setReportStatus(result);
            }
            DTResponseDto dtResponseDto = new DTResponseDto(dtRequestDto.getDraw(), count, count, dto4DTs);
            return dtResponseDto;
        }
    }


    public Integer getCoverFaultIsReport(Integer coverId) throws Exception {
        List<CoverFaultDto> coverFaultDtos = coverFaultRepository.getCoverFaultIsReport(coverId);
        Integer result = 1;
        if (coverFaultDtos.size() != 0) {
            Integer mainCheck = coverFaultDtos.get(0).getCoverMainCheck();
            Integer check = coverFaultDtos.get(0).getCoverCheck();
            Integer status = coverFaultDtos.get(0).getCoverMaintenanceStatus();
            if (status == 2) {
                result = 1;//维修完成
            } else if (mainCheck == -1 || check == -1) {
                result = 1;//
            } else {
                result = 0;
            }
        }
        return result;
    }


    public Integer reportCoverFault(final Integer coverId, Integer coverFaultCreatorId, Integer coverFaultLevel, Integer coverFaultType,
                                    String coverFaultPhoto, String coverFaultReason, Double coverMoney, final Integer coverOrgId, Integer coverMainOrgId) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        if (coverMoney == null)
            coverMoney = 0.0;
        CoverFaultDto insertDto = new CoverFaultDto();
        insertDto.setCoverId(coverId);
        insertDto.setCoverFaultCreatorId(coverFaultCreatorId);
        insertDto.setCoverFaultLevel(coverFaultLevel);
        insertDto.setCoverFaultType(coverFaultType);
        insertDto.setCoverFaultTime(df.format(new Date()));
        insertDto.setCoverFaultPhoto(coverFaultPhoto);
        insertDto.setCoverFaultReason(coverFaultReason);
        insertDto.setCoverMoney(coverMoney);
        insertDto.setCoverOrgId(coverOrgId);
        insertDto.setCoverMainOrgId(coverMainOrgId);

        List<UserDto> userDtos = userRepository.getUserIdsByOrgIdAndActorId(coverOrgId, 3);
        final String msg = "窨井 NO：" + coverId + " 待审核";
        strUserIds = "";
        for (UserDto userDto : userDtos) {
            strUserIds += userDto.getUserId().toString() + ",";
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!strUserIds.equals("")) {
                        strUserIds = strUserIds.substring(0, strUserIds.length() - 1);
                        PushUtil.sendPushToUser(strUserIds, msg);
                        PushHistoryDto pushHistoryDto = new PushHistoryDto(coverOrgId, 3, msg, formatter.format(new Date()),9);
                        pushHistoryRepository.save(pushHistoryDto.toBean());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return coverFaultRepository.save(insertDto.toBean()).getCoverId();
    }

    public List<String> getStartRoad(String roadName, Integer actorId, Integer orgId) throws Exception {
        return coverRepository.getStartRoad(roadName, actorId, orgId);
    }

    public List<String> getSectionByStartRoad(String roadName, Integer actorId, Integer orgId) throws Exception {
        return coverRepository.getSectionByStartRoad(roadName, actorId, orgId);
    }

    public List<CoverFaultDto> getCoverFaultList4App(Integer orgId, String actorIds, Integer faultStatus, Integer count, Integer size) throws Exception {
        return coverFaultRepository.getCoverFaultList4App(orgId, actorIds, faultStatus, count, size);
    }
}
